package com.fdl.tags;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;

import com.fdl.common.utils.StringUtil;

/**
 * PageControl, 分页控制, 可以判断总页数和是否有上下页.
 * 
 * 加入输出上下分页HTML代码功能
 * 
 * @author jing.qiu
 * @version 1.1 2008-9-22
 */
public class PageBean {
	/** 每页显示记录数 */
	private int pageCount;
	/** 是否有上一页 */
	private boolean hasPrevPage;
	/** 记录总数 */
	private int recordCount;
	/** 是否有下一页 */
	private boolean hasNextPage;
	/** 总页面数 */
	private int totalPage = -1;
	/** 当前页码数 */
	private int currentPage;

	/**
	 * 分页前的页面地址
	 */
	private String pageUrl;

	/**
	 * 查询条件
	 */
	private static Map query;

	/**
	 * 输出分页 HTML 页面跳转代码, 分链接和静态文字两种. 如果有查询条件，带查询条件 2008-07-22
	 * 
	 * @return HTML 代码
	 */
	public String getPageJumpLinkHtml() {
		if (isEmpty(pageUrl)) {
			return getPageJumpLinkHtmlByDeptUser();
		}
		
		String queryInfo = getQueryInfo(query);
		getTotalPage();

		// 检查是否有参数符号, 没有就加上一个?
		if (pageUrl.indexOf('?') == -1) {
			pageUrl = pageUrl + '?';
		}

		// StringBuffer buff = new StringBuffer("<div class='manu f_r'>");
		StringBuffer buff = new StringBuffer();

		/*
		 * <div class="total">共计<span class="font_bule">3</span>条</div> <div
		 * class='manu f_r'> <span class='disabled'>上一页</span> <span
		 * class="current">1</span> <a href="#">2</a> <a href="#">3</a> <a
		 * href="#">4</a> <a href="#">5</a>... <a href="#">下一页</a> 共40页　到<input
		 * type="text" name="textfield" class="jump_pages"/>页 <input
		 * type="submit" name="button" class="btn_org_short" value="确定" />
		 * </div>
		 */
		int totalPage = getTotalPage();
		// 上一页翻页标记
		if (currentPage > 1) {
			buff.append(" <a href='" + pageUrl + "&pageno=" + (currentPage - 1)
					+ "&totalpage=" + totalPage + queryInfo + "' title='转到第 "
					+ (currentPage - 1) + " 页'>上一页</a>  ");
		} else {
			buff.append(" <span class='disabled'>上一页</span> ");
		}

		// 下一页翻页标记
		if (currentPage < totalPage) {
			buff.append(" <a href='" + pageUrl + "&pageno=" + (currentPage + 1)
					+ "&totalpage=" + totalPage + queryInfo + "' title='转到第 "
					+ (currentPage + 1) + " 页'>下一页</a>  ");
		} else {
			buff.append(" <span class='disabled'>下一页</span>  ");
		}

		// buff.append("</div>");

		return buff.toString();
	}
	/**
	 * 为部门用户特定的分页代码 
	 * @return
	 * @author jing.qiu
	 */
	public String getPageJumpLinkHtmlByDeptUser() {

		String deptId=(String)query.get("departId");
		if(null!=deptId){
			getTotalPage();
			StringBuffer buff = new StringBuffer();
			int totalPage = getTotalPage();
			// 上一页翻页标记
			if (currentPage > 1) {
				buff.append("<a href='javascript:getUserInfo(" + deptId + "," + (currentPage - 1)
						+ "," + totalPage +")' title='转到第 "
						+ (currentPage - 1) + " 页'>上一页</a>  ");
			} else {
				buff.append(" <span class='disabled'>上一页</span> ");
			}
			
			// 下一页翻页标记
			if (currentPage < totalPage) {
				buff.append("<a href='javascript:getUserInfo(" + deptId + ","+(currentPage + 1)
						+ "," + totalPage + ")' title='转到第 "
						+ (currentPage + 1) + " 页'>下一页</a>  ");
			} else {
				buff.append(" <span class='disabled'>下一页</span>  ");
			}
			return buff.toString();
		}
		return "";
	}

	/**
	 * 输出页码信息: 第${currentPage}页/共${totalPage}页
	 * 
	 * @return
	 */
	public String getPageCountHtml() {
		return "&nbsp;共" + getTotalPage() + "页";
	}

	/**
	 * 输出 JavaScript 跳转函数代码
	 * 
	 * @return
	 */
	public String getJavaScriptJumpCode() {
		if (isEmpty(pageUrl)) {
			return "";
		}
		String queryInfo = getQueryInfo(query);
		// 检查是否有参数符号, 没有就加上一个?
		if (pageUrl.indexOf("?") == -1) {
			pageUrl = pageUrl + '?';
		}

		return "<script>" + "// 页面跳转函数\n" + "// 参数: 包含页码的表单元素，例如输入框，下拉框等\n"
				+ "function jumpPage(input) {\n" + "	// 页码相同就不做跳转\n"
				+ " 	if(input.value == " + currentPage + ") {" + "		return;\n"
				+ "	}" + "	var newUrl = '" + pageUrl
				+ "&pageno=' + input.value+'&totalpage=" + totalPage
				+ queryInfo + "';\n" + "	document.location = newUrl;\n"
				+ " }\n" + " </script>";

	}
	
		
	/**
	 * 输出页面跳转的选择框和输入框. 示例输出:
	 * 
	 * <pre>
	 * 转到
	 * 	  &lt;!-- 输出 HTML SELECT 元素, 并选中当前页面编码 --&gt;
	 *       &lt;select onchange='jumpPage(this);'&gt;
	 *       
	 *       &lt;c:forEach var=&quot;i&quot; begin=&quot;1&quot; end=&quot;${totalPage}&quot;&gt;
	 *         &lt;option value=&quot;${i}&quot;
	 * 		
	 * 		&lt;c:if test=&quot;${currentPage == i}&quot;&gt;
	 * 		selected
	 * 		&lt;/c:if&gt;
	 * 
	 * 	&gt;第${i}页&lt;/option&gt;
	 * 	  &lt;/c:forEach&gt;
	 * 	  
	 *       &lt;/select&gt;
	 *       输入页码：&lt;input type=&quot;text&quot; value=&quot;${currentPage}&quot; id=&quot;jumpPageBox&quot; size=&quot;3&quot;&gt; 
	 *       &lt;input type=&quot;button&quot; value=&quot;跳转&quot; onclick=&quot;jumpPage(document.getElementById('jumpPageBox'))&quot;&gt;
	 * </pre>
	 * 
	 * @return
	 */
	public String getPageFormJumpHtml() {
		/*
		 * String s = "转到\n" + "\t  <!-- 输出 HTML SELECT 元素, 并选中当前页面编码 -->\n" +
		 * "      <select onchange='jumpPage(this);'>\n" + "      \n";
		 * 
		 * for(int i = 1; i <= getTotalPage(); i++ ) { s += "<option value=" + i
		 * + "\n";
		 * 
		 * if(currentPage == i) { s+= " selected "; }
		 * 
		 * s += "\t>第" + i + "页</option>\n"; }
		 * 
		 * s+= "      </select>\n" + "      输入页码：<input type=\"text\" value=\""
		 * + currentPage + "\" id=\"jumpPageBox\" size=\"3\"> \n" +
		 * "      <input type=\"button\" value=\"跳转\" onclick=\"jumpPage(document.getElementById('jumpPageBox'))\">  "
		 * ;
		 */
		if (isEmpty(pageUrl)) {
			String deptId=(String)query.get("departId");
			if(null!=deptId){
				String s = null;
				if (totalPage > 1) {
					s = "<input type=\"text\" class='jump_pages' value=\""
							+ currentPage
							+ "\" "
							+ "id=\"jumpPageBox\" size=\"3\">页\n"
							+ "        <input class='btn_org_short' id='_jump_page_index' type=\"button\" value=\"go\" onclick=\"jumpPage("+deptId+","+totalPage+",document.getElementById('jumpPageBox'))\">  ";
				} else {
					s = "<input type=\"text\" class='jump_pages' value=\""
							+ currentPage
							+ "\" "
							+ "id=\"jumpPageBox\" size=\"3\">页 \n"
							+ "        <input class='btn_org_short' id='_jump_page_index' type=\"button\" value=\"go\" disabled=\"disabled\" onclick=\"jumpPage("+deptId+","+totalPage+",document.getElementById('jumpPageBox'))\">  ";
				}
				return s;
			}
			return "";
		}
		
		
		
		String s = null;
		if (totalPage > 1) {
			s = "<input type=\"text\" class='jump_pages' value=\""
					+ currentPage
					+ "\" "
					+ " onfocus='this.select()' onkeydown='document.getElementById(\"_jump_page_index\").click()' "
					+ "id=\"jumpPageBox\" size=\"3\">页\n"
					+ "        <input class='btn_org_short' id='_jump_page_index' type=\"button\" value=\"go\" onclick=\"jumpPage(document.getElementById('jumpPageBox'))\">  ";
		} else {
			s = "<input type=\"text\" class='jump_pages' value=\""
					+ currentPage
					+ "\" "
					+ " onfocus='this.select()' onkeydown='document.getElementById(\"_jump_page_index\").click()' "
					+ "id=\"jumpPageBox\" size=\"3\">页 \n"
					+ "        <input class='btn_org_short' id='_jump_page_index' type=\"button\" value=\"go\" disabled=\"disabled\" onclick=\"jumpPage(document.getElementById('jumpPageBox'))\">  ";
		}

		return s;
	}

	/**
	 * 进行分页计算.
	 */
	private void calculate() {
		if (getPageCount() == 0) {
			setPageCount(1);
		}

		totalPage = (int) Math.ceil(1.0 * getRecordCount() / getPageCount()); // 总页面数
		if (totalPage == 0)
			totalPage = 1;

		// Check current page range, 2006-08-03
		if (currentPage > totalPage) {
			currentPage = totalPage;
		}
		// System.out.println("currentPage=" + currentPage);
		// System.out.println("maxPage=" + maxPage);
		// // Fixed logic error at 2004-09-25
		hasNextPage = currentPage < totalPage;
		hasPrevPage = currentPage > 1;
		return;
	}

	/**
	 * @return Returns the 最大页面数.
	 */
	public int getTotalPage() {
		if (totalPage == -1) {
			calculate();
		}
		return totalPage;
	}

	/**
	 * @param currentPage
	 *            The 最大页面数 to set.
	 */
	@SuppressWarnings("unused")
	private void setTotalPage(int maxPage) {
		this.totalPage = maxPage;
	}

	/**
	 * 是否有上一页数据
	 */
	public boolean hasPrevPage() {
		calculate();
		return hasPrevPage;
	}

	/**
	 * 是否有下一页数据
	 */
	public boolean hasNextPage() {
		calculate();
		return hasNextPage;
	}

	/**
	 * 输出小脚本，里面包括当前页码
	 * 
	 * @param args
	 */
	public String pageGetInfoByJava() {
		String javaStr = "<input type=\"hidden\" value=" + currentPage
				+ " id=\"pageno\">";
		return javaStr;
	}

	/**
	 * 根据Map集合构造查询条件信息
	 * 
	 * @return
	 */
	private String getQueryInfo(Map mapQuery) {
		StringBuffer buffer = new StringBuffer("&");
		if (!StringUtil.isNull(mapQuery)) {
			Set<Entry<String, Object>> set = mapQuery.entrySet();
			if (set != null && set.size() > 0) {
				buffer.append("isTranscoding=true&");
				for (Entry<String, Object> entry : set) {
					if (!StringUtil.isNull(entry.getValue())) {
						try {
							buffer.append(entry.getKey()).append("=").append(
									java.net.URLEncoder
											.encode(java.net.URLEncoder
													.encode(entry.getValue()
															.toString(),
															"utf-8"))).append(
									"&");
						} catch (UnsupportedEncodingException e) {
							e.printStackTrace();
						}
					}
				}
			}
		}
		return buffer.substring(0, buffer.length() - 1).toString();
	}

	public static void main(String[] args) {
		PageBean page = new PageBean();
		page.setCurrentPage(3);
		page.setPageCount(20);
		page.setRecordCount(5);
		page.setTotalPage(4);
		page.setPageUrl("");
		Map map = new HashMap<String, String>();
		map.put("aaa", "张三");
		map.put("departId", "1000025");
		page.setQuery(map);

		System.out.println(page.getPageFormJumpHtml());
	}

	/**
	 * @return Returns the 当前页码数.
	 */
	public int getCurrentPage() {
		return currentPage;
	}

	/**
	 * 设置当前页码, 从 1 开始.
	 * 
	 * @param currentPage
	 *            The 当前页码数 to set.
	 */
	public void setCurrentPage(int currentPage) {
		if (currentPage <= 0) {
			currentPage = 1;
		}
		this.currentPage = currentPage;
	}

	/**
	 * @return Returns the recordCount.
	 */
	public int getRecordCount() {
		return recordCount;
	}

	/**
	 * @param recordCount
	 *            The recordCount to set.
	 */
	public void setRecordCount(int property1) {
		this.recordCount = property1;
	}

	/**
	 * @return Returns the 每页显示记录数.
	 */
	public int getPageCount() {
		return pageCount;
	}

	/**
	 * @param pageCount
	 *            The 每页显示记录数 to set.
	 */
	public void setPageCount(int pageCount) {
		this.pageCount = pageCount;
	}

	public String getPageUrl() {
		return pageUrl;
	}

	public void setPageUrl(String value) {
		pageUrl = value;
	}

	public Map getQuery() {
		return query;
	}

	public void setQuery(Map query) {
		this.query = query;
	}

	/**
	 * Checks if string is null or empty.
	 * 
	 * @param value
	 *            The string to be checked
	 * @return True if string is null or empty, otherwise false.
	 */
	public static boolean isEmpty(final String value) {
		return value == null || value.trim().length() == 0;
	}
}
